package com.ruoyi.service;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.pinyin.PinyinUtil;
import cn.hutool.system.SystemUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.CustomData;
import com.ruoyi.common.core.domain.TreeSelect;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.query.CustomDataConfigQuery;
import com.ruoyi.common.core.domain.vo.MenuRoleAuthorityVO;
import com.ruoyi.common.core.mapper.CustomDataMapper;
import com.ruoyi.common.core.mapper.SysUserMapper;
import com.ruoyi.common.core.service.BaseServiceImpl;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.entity.SysRoleMenu;
import com.ruoyi.mapper.SysMenuMapper;
import com.ruoyi.mapper.SysRoleMapper;
import com.ruoyi.mapper.SysRoleMenuMapper;
import com.ruoyi.vo.MetaVO;
import com.ruoyi.vo.RouterVO;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Scriptable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.*;
import java.util.stream.Collectors;
import static com.ruoyi.common.constant.BusinessConstant.CustomerDataType.BACK_SYSTEM;

/**
 * 菜单 业务层处理
 */
@Service
public class SysMenuServiceImpl extends BaseServiceImpl<SysMenuMapper, SysMenu> {
    @Autowired
    private SysMenuMapper menuMapper;
    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysRoleMenuMapper roleMenuMapper;

    @Autowired
    private CustomDataMapper customDataMapper;


    /**
     * 根据用户查询系统菜单列表
     *
     * @param userId 用户ID
     * @return 菜单列表
     */

    public List<SysMenu> selectMenuList(Long userId) {
        return selectMenuList(new SysMenu(), userId);
    }

    /**
     * 查询系统菜单列表
     *
     * @param menu 菜单信息
     * @return 菜单列表
     */

    public List<SysMenu> selectMenuList(SysMenu menu, Long userId) {
        List<SysMenu> menuList = null;

        // 管理员显示所有菜单信息
        if (SysUserServiceImpl.isAdmin(userId)) {
            menuList = menuMapper.selectMenuList(menu);
        } else {
            menu.getParams().put("userId", userId);
            menuList = menuMapper.selectMenuListByUserId(menu);
        }
        return menuList;
    }

    /**
     * 根据用户ID查询权限
     *
     * @param userId 用户ID
     * @return 权限列表
     */

    public Set<String> selectMenuPermsByUserId(Long userId) {
        List<String> perms = menuMapper.selectMenuPermsByUserId(userId);
        Set<String> permsSet = new HashSet<>();
        for (String perm : perms) {
            if (StringUtils.isNotEmpty(perm)) {
                permsSet.addAll(Arrays.asList(perm.trim().split(",")));
            }
        }
        return permsSet;
    }

    /**
     * 根据角色ID查询权限
     *
     * @param roleId 角色ID
     * @return 权限列表
     */

    public Set<String> selectMenuPermsByRoleId(Long roleId) {
        List<String> perms = menuMapper.selectMenuPermsByRoleId(roleId);
        Set<String> permsSet = new HashSet<>();
        for (String perm : perms) {
            if (StringUtils.isNotEmpty(perm)) {
                permsSet.addAll(Arrays.asList(perm.trim().split(",")));
            }
        }
        return permsSet;
    }

    /**
     * 根据用户ID查询菜单
     *
     * @param userId 用户名称
     * @return 菜单列表
     */

    public List<SysMenu> selectMenuTreeByUserId(Long userId) {
        List<SysMenu> menus = null;
        if (SysUserServiceImpl.isAdmin(userId)) {
            menus = menuMapper.selectMenuTreeAll();
        } else {
            menus = menuMapper.selectMenuTreeByUserId(userId);
        }
        return getChildPerms(menus, 0);
    }

    /**
     * 根据角色ID查询菜单树信息
     *
     * @param roleId 角色ID
     * @return 选中菜单列表
     */

    public List<Long> selectMenuListByRoleId(Long roleId) {
        SysRole role = roleMapper.selectRoleById(roleId);
        return menuMapper.selectMenuListByRoleId(roleId, role.getMenuCheckStrictly());
    }

    /**
     * 构建前端路由所需要的菜单
     *
     * @param menus 菜单列表
     * @return 路由列表
     */

    public List<RouterVO> buildMenus(List<SysMenu> menus) {
        List<RouterVO> routers = new LinkedList<RouterVO>();
        for (SysMenu menu : menus) {
            RouterVO router = new RouterVO();
            router.setHidden(menu.getVisible());
            router.setName(getRouteName(menu));
            router.setPath(getRouterPath(menu));
            router.setComponent(getComponent(menu));
            router.setQuery(menu.getQuery());
            router.setMeta(new MetaVO(menu.getMenuName(), menu.getIcon(), !menu.getCache(), menu.getPath()));
            List<SysMenu> cMenus = menu.getChildren();
            if (StringUtils.isNotEmpty(cMenus) && UserConstants.TYPE_DIR.equals(menu.getMenuType())) {
                router.setAlwaysShow(true);
                router.setRedirect("noRedirect");
                router.setChildren(buildMenus(cMenus));
            } else if (isMenuFrame(menu)) {
                router.setMeta(null);
                List<RouterVO> childrenList = new ArrayList<RouterVO>();
                RouterVO children = new RouterVO();
                children.setPath(menu.getPath());
                children.setComponent(menu.getComponent());
                children.setName(StringUtils.capitalize(menu.getPath()));
                children.setMeta(new MetaVO(menu.getMenuName(), menu.getIcon(), !menu.getCache(), menu.getPath()));
                children.setQuery(menu.getQuery());
                childrenList.add(children);
                router.setChildren(childrenList);
            } else if (menu.getParentId().intValue() == 0 && isInnerLink(menu)) {
                router.setMeta(new MetaVO(menu.getMenuName(), menu.getIcon()));
                router.setPath("/");
                List<RouterVO> childrenList = new ArrayList<RouterVO>();
                RouterVO children = new RouterVO();
                String routerPath = innerLinkReplaceEach(menu.getPath());
                children.setPath(routerPath);
                children.setComponent(UserConstants.INNER_LINK);
                children.setName(StringUtils.capitalize(routerPath));
                children.setMeta(new MetaVO(menu.getMenuName(), menu.getIcon(), menu.getPath()));
                childrenList.add(children);
                router.setChildren(childrenList);
            }
            routers.add(router);
        }
        return routers;
    }

    /**
     * 构建前端所需要树结构
     *
     * @param menus 菜单列表
     * @return 树结构列表
     */

    public List<SysMenu> buildMenuTree(List<SysMenu> menus) {
        List<SysMenu> returnList = new ArrayList<SysMenu>();
        List<Long> tempList = menus.stream().map(SysMenu::getMenuId).collect(Collectors.toList());
        for (Iterator<SysMenu> iterator = menus.iterator(); iterator.hasNext(); ) {
            SysMenu menu = (SysMenu) iterator.next();
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(menu.getParentId())) {
                recursionFn(menus, menu);
                returnList.add(menu);
            }
        }
        if (returnList.isEmpty()) {
            returnList = menus;
        }
        return returnList;
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param menus 菜单列表
     * @return 下拉树结构列表
     */

    public List<TreeSelect> buildMenuTreeSelect(List<SysMenu> menus) {
        List<SysMenu> menuTrees = buildMenuTree(menus);
        return menuTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    /**
     * 根据菜单ID查询信息
     *
     * @param menuId 菜单ID
     * @return 菜单信息
     */

    public SysMenu selectMenuById(Long menuId) {
        return menuMapper.selectMenuById(menuId);
    }

    /**
     * 是否存在菜单子节点
     *
     * @param menuId 菜单ID
     * @return 结果
     */

    public boolean hasChildByMenuId(Long menuId) {
        int result = menuMapper.hasChildByMenuId(menuId);
        return result > 0;
    }

    /**
     * 查询菜单使用数量
     *
     * @param menuId 菜单ID
     * @return 结果
     */

    public boolean checkMenuExistRole(Long menuId) {
        int result = roleMenuMapper.checkMenuExistRole(menuId);
        return result > 0;
    }

    /**
     * 新增保存菜单信息
     *
     * @param menu 菜单信息
     * @return 结果
     */

    public int insertMenu(SysMenu menu) {
        menu.insert();
        return 1;
    }

    /**
     * 修改保存菜单信息
     *
     * @param menu 菜单信息
     * @return 结果
     */

    public int updateMenu(SysMenu menu) {
        menu.updateById();
        return 1;
    }

    /**
     * 删除菜单管理信息
     *
     * @param menuId 菜单ID
     * @return 结果
     */

    public int deleteMenuById(Long menuId) {
        return menuMapper.deleteMenuById(menuId);
    }

    /**
     * 校验菜单名称是否唯一
     *
     * @param menu 菜单信息
     * @return 结果
     */

    public boolean checkMenuNameUnique(SysMenu menu) {
        Long menuId = StringUtils.isNull(menu.getMenuId()) ? -1L : menu.getMenuId();
        SysMenu info = menuMapper.checkMenuNameUnique(menu.getMenuName(), menu.getParentId());
        if (StringUtils.isNotNull(info) && info.getMenuId().longValue() != menuId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 获取路由名称
     *
     * @param menu 菜单信息
     * @return 路由名称
     */
    public String getRouteName(SysMenu menu) {
        String routerName = StringUtils.capitalize(menu.getPath());
        // 非外链并且是一级目录（类型为目录）
        if (isMenuFrame(menu)) {
            routerName = StringUtils.EMPTY;
        }
        return routerName;
    }

    /**
     * 获取路由地址
     *
     * @param menu 菜单信息
     * @return 路由地址
     */
    public String getRouterPath(SysMenu menu) {
        String routerPath = menu.getPath();
        // 内链打开外网方式
        if (menu.getParentId().intValue() != 0 && isInnerLink(menu)) {
            routerPath = innerLinkReplaceEach(routerPath);
        }
        // 非外链并且是一级目录（类型为目录）
        if (0 == menu.getParentId().intValue() && UserConstants.TYPE_DIR.equals(menu.getMenuType())
                && !menu.getFrame()) {
            routerPath = "/" + menu.getPath();
        }
        // 非外链并且是一级目录（类型为菜单）
        else if (isMenuFrame(menu)) {
            routerPath = "/";
        }
        return routerPath;
    }

    /**
     * 获取组件信息
     *
     * @param menu 菜单信息
     * @return 组件信息
     */
    public String getComponent(SysMenu menu) {
        String component = UserConstants.LAYOUT;
        if (StringUtils.isNotEmpty(menu.getComponent()) && !isMenuFrame(menu)) {
            component = menu.getComponent();
        } else if (StringUtils.isEmpty(menu.getComponent()) && menu.getParentId().intValue() != 0 && isInnerLink(menu)) {
            component = UserConstants.INNER_LINK;
        } else if (StringUtils.isEmpty(menu.getComponent()) && isParentView(menu)) {
            component = UserConstants.PARENT_VIEW;
        }
        return component;
    }

    /**
     * 是否为菜单内部跳转
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isMenuFrame(SysMenu menu) {
        return menu.getParentId().intValue() == 0 && UserConstants.TYPE_MENU.equals(menu.getMenuType())
                && !menu.getFrame();
    }

    /**
     * 是否为内链组件
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isInnerLink(SysMenu menu) {
        return !menu.getFrame() && StringUtils.ishttp(menu.getPath());
    }

    /**
     * 是否为parent_view组件
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isParentView(SysMenu menu) {
        return menu.getParentId().intValue() != 0 && UserConstants.TYPE_DIR.equals(menu.getMenuType());
    }

    /**
     * 根据父节点的ID获取所有子节点
     *
     * @param list     分类表
     * @param parentId 传入的父节点ID
     * @return String
     */
    public List<SysMenu> getChildPerms(List<SysMenu> list, int parentId) {
        List<SysMenu> returnList = new ArrayList<SysMenu>();
        for (Iterator<SysMenu> iterator = list.iterator(); iterator.hasNext(); ) {
            SysMenu t = (SysMenu) iterator.next();
            // 一、根据传入的某个父节点ID,遍历该父节点的所有子节点
            if (t.getParentId() == parentId) {
                recursionFn(list, t);
                returnList.add(t);
            }
        }
        return returnList;
    }

    /**
     * 递归列表
     *
     * @param list 分类表
     * @param t    子节点
     */
    private void recursionFn(List<SysMenu> list, SysMenu t) {
        // 得到子节点列表
        List<SysMenu> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysMenu tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<SysMenu> getChildList(List<SysMenu> list, SysMenu t) {
        List<SysMenu> tlist = new ArrayList<SysMenu>();
        Iterator<SysMenu> it = list.iterator();
        while (it.hasNext()) {
            SysMenu n = (SysMenu) it.next();
            if (n.getParentId().longValue() == t.getMenuId().longValue()) {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysMenu> list, SysMenu t) {
        return getChildList(list, t).size() > 0;
    }

    /**
     * 内链域名特殊字符替换
     *
     * @return 替换后的内链域名
     */
    public String innerLinkReplaceEach(String path) {
        return StringUtils.replaceEach(path, new String[]{Constants.HTTP, Constants.HTTPS, Constants.WWW, "."},
                new String[]{"", "", "", "/"});
    }

    public Object routerGetList(String terminal) throws Exception {
        //routerSave("");
        List<SysMenu> actionList = baseMapper.selectMenuTree(terminal, "v2");
        List<SysRoleMenu> roleMenuList = roleMenuMapper.findAll();
        List<Tree<Long>> tree = TreeUtil.build(actionList, 0L, new TreeNodeConfig().setChildrenKey("children").setIdKey("menuId").setParentIdKey("parentId").setNameKey("name"),
                (menu, treeNode) -> {
                    treeNode.put("menuId", menu.getMenuId());
                    treeNode.put("name", menu.getMenuId());
                    treeNode.put("fullPath", getFullPath(actionList, menu, ""));
                    treeNode.put("path", menu.getPath());
                    treeNode.put("order_flag", menu.getOrderNum());
                    treeNode.put("component", menu.getComponent());
                    treeNode.put("parentId", menu.getParentId());
                    treeNode.put("meta", menu.getMeta());
                    List<Long> authorizedRoleIds = roleMenuList.stream().filter(r -> r.getMenuId().equals(menu.getMenuId())).map(r -> r.getRoleId()).collect(Collectors.toList());
                    treeNode.put("authorizedRoleIds", authorizedRoleIds);
                });
        return tree;
    }


    //获取全路径
    public String getFullPath(List<SysMenu> actionList, SysMenu current, String path) {
        SysMenu parent = actionList.stream().filter(r -> r.getMenuId().equals(current.getParentId())).findAny().orElse(null);
        path = current.getPath() + (StrUtil.isBlank(path) ? "" : ("/" + path));
        if (parent == null) {
            return path;
        } else {
            path = getFullPath(actionList, parent, path);
        }
        path = path.replaceAll("[\\\\/]+", "/");
        return path;
    }

    //获取全路径
    public String getFullPath(SysMenu current, String path) {
        SysMenu parent = baseMapper.selectMenuById(current.getParentId());
        path = current.getPath() + (StrUtil.isBlank(path) ? "" : ("/" + path));
        if (parent == null) {
            return path;
        } else {
            path = getFullPath(parent, path);
        }
        path = path.replaceAll("[\\\\/]+", "/");
        if (path != null && !path.startsWith("/")) {
            path = "/" + path;
        }
        return path;
    }

    public Object routerSave(String json) throws Exception {
        // 创建脚本引擎
        Context cx = Context.enter();
        Scriptable scope = cx.initStandardObjects();
        String jsCode = FileUtil.readUtf8String("D:\\git-projects\\study\\ruoyi-system\\src\\main\\java\\com\\ruoyi\\system\\service\\router2.json");
        Object result = cx.evaluateString(scope, jsCode, "<cmd>", 1, null);
        json = JSON.toJSONString(result);
        JSONArray allNode = JSON.parseArray(json);
        eachArray(allNode, 0L);
        return "";
    }

    public Object eachArray(JSONArray allNode, Long pid) {
        for (int i = 0; i < allNode.size(); i++) {
            JSONObject row = allNode.getJSONObject(i);
            SysMenu menu = JSON.parseObject(row.toJSONString(), SysMenu.class);
            menu.setParentId(pid);
            menu.setVersion("v2");
            menu.setOrderNum(i);
            menu.setMenuName(menu.getMeta().getTitle());
            menu.insert();
            menu.setName(menu.getMenuId() + "");
            menu.updateById();
            if (menu.getChildren().size() > 0) {
                eachArray(row.getJSONArray("children"), menu.getMenuId());
            }
        }
        return "";
    }

    public void doSaveMeta(CustomDataConfigQuery customDataConfig) {
        SysMenu menu = menuMapper.selectById(customDataConfig.getId());
        SysUser user = userMapper.selectById(SecurityUtils.getUserId());
        Assert.isFalse(!SystemUtil.getOsInfo().isWindows() && !"password".equals(user.getRemark())
                , "只能工程师本地使用");
        CustomData customData = customDataMapper.getByOwnerId(BACK_SYSTEM, customDataConfig.getId());
        if (customData == null) {
            customData = new CustomData();
        }
        customData.setData_name(menu.getMeta().getTitle());
        customData.setType(BACK_SYSTEM);
        customData.setOwnerId(customDataConfig.getId());
        customData.setAttr(customDataConfig.getAttr());
        customData.setQuerySql(customDataConfig.getSql());
        customData.insertOrUpdate();
    }

    public void doSave(SysMenu action) {
        action.setMenuName(action.getMeta().getTitle());
        if (action.getMenuId() == null) {
            action.insert();
            action.setName(action.getMenuId() + "");
            action.updateById();
        }
        if (!action.getMeta().isCustomPath()) {
            action.setPath(PinyinUtil.getFirstLetter(action.getMeta().getTitle(), ""));
        }
        if (action.getOrderNum() == null) {
            List<SysMenu> list = baseMapper.selectByPid(action.getParentId());
            action.setOrderNum((list.size() + 1));
        }
        action.insertOrUpdate();
        action.setFullPath(getFullPath(action, ""));
        action.updateById();
    }

    public SysMenu getInfo(Long id) {
        SysMenu action = baseMapper.selectById(id);
        return action;
    }

    public void doCopy(SysMenu action) {
        SysMenu menu = baseMapper.selectById(action.getMenuId());
        menu.setMenuId(null);
        menu.insert();

        CustomData customData = customDataMapper.getByOwnerId(BACK_SYSTEM, action.getMenuId() + "");
        if (customData != null) {
            customData.setId(null);
            customData.setOwnerId(menu.getMenuId() + "");
            customData.insert();
        }
    }

    public void doDelete(SysMenu action) {
        List<SysMenu> childList = baseMapper.selectByPid(action.getMenuId());
        Assert.isFalse(childList.size() > 0, "存在子节点不能删除");
        action.deleteById();
        CustomData customData = customDataMapper.getByOwnerId(BACK_SYSTEM, action.getMenuId() + "");
        if (customData != null) {
            customData.deleteById();
        }
    }


    public Object getAuthorityMenuList(String terminal) throws Exception {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        //routerSave("");
        List<SysMenu> allActionList = baseMapper.selectMenuTree(terminal, "v2");
        List<SysMenu> hiddenMenuList = allActionList.stream().filter(r -> r.getMeta().isHidden()).collect(Collectors.toList());
        List<SysMenu> actionList = baseMapper.getAuthorityMenuList(user.getUserId());

        //有权限的菜单与隐藏菜单合并
        List<SysMenu> newActionList = new ArrayList<>();
        actionList.addAll(hiddenMenuList);
        newActionList.addAll(actionList);

        //追加父菜单
        for (int i = 0; i < actionList.size(); i++) {
            SysMenu menu = actionList.get(i);
            addParentMenu(menu, newActionList);
        }

        //如果子节点全部隐藏，则父节点也隐藏
        newActionList.forEach(r -> {
            if ("Layout".equals(r.getComponent())) {
                boolean noShowChild = newActionList.stream().filter(
                        t1 -> !t1.getMeta().isHidden() && t1.getParentId().intValue() == r.getMenuId().intValue()).count() == 0;
                if (noShowChild && !r.getMeta().isHidden()) {
                    r.getMeta().setHidden(true);
                    r.toJson();
                }
            }
        });

        List<Tree<Long>> tree = TreeUtil.build(newActionList, 0L, new TreeNodeConfig().setChildrenKey("children").setIdKey("menuId").setParentIdKey("parentId").setNameKey("name"),
                (menu, treeNode) -> {
                    treeNode.put("menuId", menu.getMenuId());
                    treeNode.put("name", menu.getMenuId());
                    treeNode.put("fullPath", getFullPath(newActionList, menu, ""));
                    treeNode.put("path", menu.getPath());
                    treeNode.put("order_flag", menu.getOrderNum());
                    treeNode.put("component", menu.getComponent());
                    treeNode.put("parentId", menu.getParentId());
                    addBadge(menu);
                    treeNode.put("meta", menu.getMeta());
                });
        log.error(JSON.toJSONString(tree));
        return tree;
    }

    public Object getMenuListForRoleAuthority() throws Exception {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        List<SysMenu> allActionList = baseMapper.selectMenuTree("5", "v2");
        List<SysMenu> hiddenMenuList = allActionList.stream().filter(r -> r.getMeta().isHidden()).collect(Collectors.toList());
        List<SysMenu> actionList = baseMapper.getAuthorityMenuList(user.getUserId());
        List<Long> hasMenuList = actionList.stream().map(r -> r.getMenuId()).collect(Collectors.toList());
        hiddenMenuList = hiddenMenuList.stream().filter(r->hasMenuList.contains(r.getMenuId())).collect(Collectors.toList());

        //有权限的菜单与隐藏菜单合并
        List<SysMenu> newActionList = new ArrayList<>();
        actionList.addAll(hiddenMenuList);
        newActionList.addAll(actionList);

        //追加父菜单
        for (int i = 0; i < actionList.size(); i++) {
            SysMenu menu = actionList.get(i);
            addParentMenu(menu, newActionList);
        }

        //如果子节点全部隐藏，则父节点也隐藏
        newActionList.forEach(r -> {
            if ("Layout".equals(r.getComponent())) {
                boolean noShowChild = newActionList.stream().filter(
                        t1 -> !t1.getMeta().isHidden() && t1.getParentId().intValue() == r.getMenuId().intValue()).count() == 0;
                if (noShowChild && !r.getMeta().isHidden()) {
                    r.getMeta().setHidden(true);
                    r.toJson();
                }
            }
        });

        List<Tree<Long>> tree = TreeUtil.build(newActionList, 0L, new TreeNodeConfig().setChildrenKey("children").setIdKey("menuId").setParentIdKey("parentId").setNameKey("name"),
                (menu, treeNode) -> {
                    treeNode.put("menuId", menu.getMenuId());
                    treeNode.put("name", menu.getMenuId());
                    treeNode.put("fullPath", getFullPath(newActionList, menu, ""));
                    treeNode.put("path", menu.getPath());
                    treeNode.put("order_flag", menu.getOrderNum());
                    treeNode.put("component", menu.getComponent());
                    treeNode.put("parentId", menu.getParentId());
                    addBadge(menu);
                    treeNode.put("meta", menu.getMeta());
                });
        log.error(JSON.toJSONString(tree));
        return tree;
    }

    private void addBadge(SysMenu menu) {
        /*if ("事项确认".equals(menu.getMeta().getTitle())) {
            long count = customDataMapper.countDemandConfirm(SecurityUtils.getUserId());
            if (count > 0) {
                menu.getMeta().setBadge(count + "");
                menu.toJson();
            }
        } else if ("任务验收".equals(menu.getMeta().getTitle())) {
            long count = customDataMapper.countTaskCheck(SecurityUtils.getUserId());
            if (count > 0) {
                menu.getMeta().setBadge(count + "");
                menu.toJson();
            }
        }*/
    }

    public void addParentMenu(SysMenu menu, List<SysMenu> newActionList) {
        if (menu == null) {
            return;
        }
        if (!newActionList.contains(menu)) {
            newActionList.add(menu);
        }
        if (menu.getParentId().intValue() == 0) {
            return;
        }
        SysMenu parentMenu = newActionList.stream().filter(r -> r.getMenuId().intValue() == menu.getParentId().intValue()).findAny().orElse(null);
        if (parentMenu == null) {
            parentMenu = baseMapper.selectById(menu.getParentId());
        }
        addParentMenu(parentMenu, newActionList);
    }


    /**
     * 获取有权限的菜单列表
     */
    public List<Tree<Long>> authorityMenuList() {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        //routerSave("");
        List<SysMenu> allActionList = baseMapper.selectMenuTree(null, "v2");
        List<SysMenu> hiddenMenuList = allActionList.stream().filter(r -> r.getMeta().isHidden()).collect(Collectors.toList());
        List<SysMenu> actionList = baseMapper.getAuthorityMenuList(user.getUserId());

        //有权限的菜单与隐藏菜单合并
        List<SysMenu> newActionList = new ArrayList<>();
        actionList.addAll(hiddenMenuList);
        newActionList.addAll(actionList);

        //追加父菜单
        for (int i = 0; i < actionList.size(); i++) {
            SysMenu menu = actionList.get(i);
            addParentMenu(menu, newActionList);
        }

        //如果子节点全部隐藏，则父节点也隐藏
        newActionList.forEach(r -> {
            if ("Layout".equals(r.getComponent())) {
                boolean noShowChild = newActionList.stream().filter(
                        t1 -> !t1.getMeta().isHidden() && t1.getParentId().intValue() == r.getMenuId().intValue()).count() == 0;
                if (noShowChild && !r.getMeta().isHidden()) {
                    r.getMeta().setHidden(true);
                    r.toJson();
                }
            }
        });

        List<Tree<Long>> tree = TreeUtil.build(newActionList, 0L, new TreeNodeConfig().setChildrenKey("children").setIdKey("menuId").setParentIdKey("parentId").setNameKey("name"),
                (menu, treeNode) -> {
                    treeNode.put("menuId", menu.getMenuId());
                    treeNode.put("name", menu.getMenuId());
                    treeNode.put("fullPath", getFullPath(newActionList, menu, ""));
                    treeNode.put("path", menu.getPath());
                    treeNode.put("order_flag", menu.getOrderNum());
                    treeNode.put("component", menu.getComponent());
                    treeNode.put("parentId", menu.getParentId());
                    addBadge(menu);
                    treeNode.put("meta", menu.getMeta());
                });
        return tree;
    }

    public void roleAuthority(MenuRoleAuthorityVO menuRoleAuthority) {
        for (int i = 0; i <menuRoleAuthority.getRoleIdList().size() ; i++) {
            Long roleId = menuRoleAuthority.getRoleIdList().get( i);
            SysRoleMenu old = roleMenuMapper.findByRoleIdAndMenuId(roleId,menuRoleAuthority.getMenuId());
            if(old != null){
                continue;
            }
            SysRoleMenu  roleMenu = new SysRoleMenu();
            roleMenu.setRoleId(roleId);
            roleMenu.setMenuId(menuRoleAuthority.getMenuId());
            roleMenuMapper.insert(roleMenu);
        }
    }
}
